//
//  StrengtheningMemoryViewController.m
//  Drivers
//
//  Created by Hunk on 10-11-1.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "StrengtheningMemoryViewController.h"
#import "ReadFile.h"
#import <AudioToolbox/AudioToolbox.h>

@interface StrengtheningMemoryViewController (Private)

- (void)getQuestion:(int)nQuestionNumber;

- (void)viewFlip:(NSString*)flipMode;

- (void)noStrengtheningMemory;

- (void)addLabelText:(UILabel*)label labelText:(NSString*)labelText;

@end


#define TITLE_ALERT_HASBEENADDED @"此题已经添加过,请勿重复添加"

#define TITLE_ALERT_FIRSTQUESTION @"这已经是第一题了"

#define TITLE_ALERT_LASTQUESTION @"这已经是最后一题了"


@implementation StrengtheningMemoryViewController
@synthesize m_pAnswerALabel;
@synthesize m_pAnswerBLabel;
@synthesize m_pAnswerCLabel;
@synthesize m_pAnswerDLabel;
@synthesize m_pPrevButton;
@synthesize m_pNextButton;
@synthesize m_pRightAnswerLabel;
@synthesize m_pImageView;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    [super viewDidLoad];
    
    UIImage *image = [UIImage imageNamed:@"cell_background.png"];
    [_bgImageView setImage:[image stretchableImageWithLeftCapWidth:5 topCapHeight:5]];
    
    [UIView viewLayerCorner:m_pPrevButton];
    [UIView viewLayerCorner:m_pNextButton];
	
	m_nCurQuestionNumber = 0;
	m_arrayOfStrengtheningMemory = [[NSMutableArray alloc] init];
	
	// Init Question label
	m_pQuestionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
	m_pQuestionLabel.numberOfLines = 0;
	m_pQuestionLabel.backgroundColor = [UIColor clearColor];	
	m_pQuestionLabel.textColor = [UIColor blackColor];
	m_pQuestionLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:18];
	m_pQuestionLabel.textAlignment = UITextAlignmentLeft;
	[self addLabelText:m_pQuestionLabel labelText:nil];
	[self.view addSubview:m_pQuestionLabel];
	
	
	ReadFile* readFile = [[ReadFile alloc] init];
	BOOL bIsFileCanBeOpened = [readFile OpenFile:@"StrengtheningMemory.sg"];
	if(bIsFileCanBeOpened)
	{
		// Get file path
		NSString* strFilePath = [readFile ReadString];
		
		NSMutableArray* _tempArrayOfStrengtheningMemory = [[NSMutableArray alloc] initWithContentsOfFile:strFilePath];
		[m_arrayOfStrengtheningMemory addObjectsFromArray:_tempArrayOfStrengtheningMemory];
		[_tempArrayOfStrengtheningMemory release];
		
		if(0 == [m_arrayOfStrengtheningMemory count])
		{
			// Show no strengthening memory question
			[self noStrengtheningMemory];
			
			return;
		}
		
		// Set title
		[self.navigationController.visibleViewController setTitle:[NSString stringWithFormat:@"共%d题,第%d题", [m_arrayOfStrengtheningMemory count], 1]];
		
		[readFile CloseFile];
		[readFile release];
		
		// Get question
		[self getQuestion:0];
	}
	else
	{
		// Show no strengthening memory question
		[self noStrengtheningMemory];
	}	
}

#pragma mark -
#pragma mark Refresh button handle
/*
- (IBAction)RefreshButtonHandle:(id)sender
{
	[m_arrayOfStrengtheningMemory removeAllObjects];
	
	ReadFile* readFile = [[ReadFile alloc] init];
	BOOL bIsFileCanBeOpened = [readFile OpenFile:@"StrengtheningMemory.sg"];
	if(bIsFileCanBeOpened)
	{
		// Get file path
		NSString* strFilePath = [readFile ReadString];
		 
		NSMutableArray* _tempArrayOfStrengtheningMemory = [[NSMutableArray alloc] initWithContentsOfFile:strFilePath];
		[m_arrayOfStrengtheningMemory addObjectsFromArray:_tempArrayOfStrengtheningMemory];
		[_tempArrayOfStrengtheningMemory release];
		
		[readFile CloseFile];
		[readFile release];
		
		// Get question
		[self getQuestion:m_nCurQuestionNumber];
	}
	else
	{
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"暂时没有强化记忆题目记录"
															message:nil
														   delegate:self 
												  cancelButtonTitle:@"哦,知道了" 
												  otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}	
}
*/
#pragma mark -
#pragma mark Get question
- (void)getQuestion:(int)nQuestionNumber
{
	// Set title
	[self.navigationController.visibleViewController setTitle:[NSString stringWithFormat:@"共%d题,第%d题", [m_arrayOfStrengtheningMemory count], (nQuestionNumber + 1)]];

	// Get the first question from the strengthening memory question array
	NSArray* arrayOfQuestion = [m_arrayOfStrengtheningMemory objectAtIndex:nQuestionNumber];
	
	// Add label text
	[self addLabelText:m_pQuestionLabel labelText:[arrayOfQuestion objectAtIndex:0]];
	
	//[m_pQuestionLabel setText:[arrayOfQuestion objectAtIndex:0]];
	
	if([arrayOfQuestion count] >= 7)
	{
		m_pAnswerALabel.hidden = NO;
		m_pAnswerBLabel.hidden = NO;
		m_pAnswerCLabel.hidden = NO;
		m_pAnswerDLabel.hidden = NO;
		
		[m_pAnswerALabel setText:[@"A:" stringByAppendingString:[arrayOfQuestion objectAtIndex:1]]];
		[m_pAnswerBLabel setText:[@"B:" stringByAppendingString:[arrayOfQuestion objectAtIndex:2]]];
		[m_pAnswerCLabel setText:[@"C:" stringByAppendingString:[arrayOfQuestion objectAtIndex:3]]];
		[m_pAnswerDLabel setText:[@"D:" stringByAppendingString:[arrayOfQuestion objectAtIndex:4]]];
		[m_pRightAnswerLabel setText:[@"正确答案:" stringByAppendingString:[arrayOfQuestion objectAtIndex:5]]];
		
		m_pImageView.alpha = 0.f;
		
		if(7 == [arrayOfQuestion count])
		{
			m_pImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[arrayOfQuestion objectAtIndex:6]]];
			
			float fWidth = m_pImageView.frame.size.width;
			float fHeight = m_pImageView.frame.size.height;
			m_pImageView.alpha = 1.f;
			
			[m_pImageView setFrame:CGRectMake((320 - fWidth)/2, m_pQuestionLabel.frame.size.height + 20, fWidth, fHeight)];
			[self.view addSubview:m_pImageView];
			[m_pImageView release];
		}		
	}
	else if([arrayOfQuestion count] == 6)
	{
		if([[arrayOfQuestion objectAtIndex:1] length] == 1)
		{
			m_pAnswerALabel.hidden = YES;
			m_pAnswerBLabel.hidden = YES;
			m_pAnswerCLabel.hidden = NO;
			m_pAnswerDLabel.hidden = NO;
			
			[m_pAnswerCLabel setText:@"正确"];
			[m_pAnswerDLabel setText:@"错误"];
			NSString* strRAnswer = [[NSString alloc] init];
			if([[arrayOfQuestion objectAtIndex:1] isEqualToString:@"C"])
			{
				strRAnswer = @"正确";
			}
			else if([[arrayOfQuestion objectAtIndex:1] isEqualToString:@"D"])
			{
				strRAnswer = @"错误";
			}
			
			[m_pRightAnswerLabel setText:[@"正确答案:" stringByAppendingString:strRAnswer]];
			[strRAnswer release];
			strRAnswer = nil;
			
			m_pImageView.alpha = 0.f;
		}
		else
		{
			m_pAnswerALabel.hidden = NO;
			m_pAnswerBLabel.hidden = NO;
			m_pAnswerCLabel.hidden = NO;
			m_pAnswerDLabel.hidden = NO;
			
			[m_pAnswerALabel setText:[@"A:" stringByAppendingString:[arrayOfQuestion objectAtIndex:1]]];
			[m_pAnswerBLabel setText:[@"B:" stringByAppendingString:[arrayOfQuestion objectAtIndex:2]]];
			[m_pAnswerCLabel setText:[@"C:" stringByAppendingString:[arrayOfQuestion objectAtIndex:3]]];
			[m_pAnswerDLabel setText:[@"D:" stringByAppendingString:[arrayOfQuestion objectAtIndex:4]]];
			[m_pRightAnswerLabel setText:[@"正确答案:" stringByAppendingString:[arrayOfQuestion objectAtIndex:5]]];
			
			m_pImageView.alpha = 0.f;			
		}
	}
	else
	{
		m_pAnswerALabel.hidden = YES;
		m_pAnswerBLabel.hidden = YES;
		m_pAnswerCLabel.hidden = NO;
		m_pAnswerDLabel.hidden = NO;
		
		[m_pAnswerCLabel setText:@"正确"];
		[m_pAnswerDLabel setText:@"错误"];
		NSString* strRAnswer = [[NSString alloc] init];
		if([[arrayOfQuestion objectAtIndex:1] isEqualToString:@"C"])
		{
			strRAnswer = @"正确";
		}
		else if([[arrayOfQuestion objectAtIndex:1] isEqualToString:@"D"])
		{
			strRAnswer = @"错误";
		}
		
		[m_pRightAnswerLabel setText:[@"正确答案:" stringByAppendingString:strRAnswer]];
		[strRAnswer release];
		strRAnswer = nil;
		
		m_pImageView.alpha = 0.f;
		
		if(3 == [arrayOfQuestion count])
		{
			m_pImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[arrayOfQuestion objectAtIndex:2]]];
			
			float fWidth = m_pImageView.frame.size.width;
			float fHeight = m_pImageView.frame.size.height;
			m_pImageView.alpha = 1.f;
			
			[m_pImageView setFrame:CGRectMake((320 - fWidth)/2, m_pQuestionLabel.frame.size.height + 50, fWidth, fHeight)];
			[self.view addSubview:m_pImageView];
			[m_pImageView release];
		}		
	}
}

#pragma mark -
#pragma mark Prev page button handle
- (IBAction)prevPage:(id)sender
{
	m_nCurQuestionNumber--;
	if(m_nCurQuestionNumber < 0)
	{
		m_nCurQuestionNumber++;
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:TITLE_ALERT_FIRSTQUESTION
															message:nil
														   delegate:self 
												  cancelButtonTitle:@"哦,知道了" 
												  otherButtonTitles: nil];
		[alertView show];
		[alertView release];
		return;
	}
	
	// View flip
	[self viewFlip:@"Down"];	
	
	// Get question
	[self getQuestion:m_nCurQuestionNumber];
}

#pragma mark -
#pragma mark Next page button handle
- (IBAction)nextPage:(id)sender
{
	m_nCurQuestionNumber++;
	if(m_nCurQuestionNumber > ([m_arrayOfStrengtheningMemory count] - 1))
	{
		m_nCurQuestionNumber--;
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:TITLE_ALERT_LASTQUESTION
															message:nil
														   delegate:self 
												  cancelButtonTitle:@"哦,知道了" 
												  otherButtonTitles: nil];
		[alertView show];
		[alertView release];
		return;
	}
	
	// View flip
	[self viewFlip:@"Up"];
	
	// Get question
	[self getQuestion:m_nCurQuestionNumber];
}

#pragma mark -
#pragma mark View flip
- (void)viewFlip:(NSString*)flipMode
{
	[UIView beginAnimations:@"View Flip" context:nil];
	[UIView setAnimationDuration:1.f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	
	if([flipMode isEqualToString:@"Up"])
	{
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
	}
	else if([flipMode isEqualToString:@"Down"])
	{
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
	}
	[self viewWillAppear:YES];
	[UIView commitAnimations];
	
	// Play effect
	NSString* effectPath = [[NSBundle mainBundle] pathForResource:@"FlipPage" ofType:@"caf"];
	SystemSoundID soundID;
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:effectPath], &soundID);
	AudioServicesPlaySystemSound(soundID);
}

#pragma mark -
#pragma mark NO strengthening memory question
- (void)noStrengtheningMemory
{
	// Set title
	[self.navigationController.visibleViewController setTitle:@"没有强化记忆题目"];
	m_pNextButton.hidden = YES;
	m_pPrevButton.hidden = YES;
	
	// Alert
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"暂时没有强化记忆题目记录"
														message:nil
													   delegate:self 
											  cancelButtonTitle:@"哦,知道了" 
											  otherButtonTitles:nil];
	[alertView show];
	[alertView release];	
}

#pragma mark -
#pragma mark - Add label text
- (void)addLabelText:(UILabel*)label labelText:(NSString*)labelText
{
	label.text = labelText;
	
	CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(300, 500) lineBreakMode:UILineBreakModeCharacterWrap];
	
	label.frame = CGRectMake(15, 10, size.width, size.height);
}

#pragma mark -
#pragma mark - alertView:clickedButtonAtIndex:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView.title isEqualToString:@"暂时没有强化记忆题目记录"])
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return NO;//(interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc 
{
	[m_arrayOfStrengtheningMemory release];
	
    [super dealloc];
}


@end
